package xuli.servlet;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;

import com.alibaba.fastjson.JSON;
import entity.Order_Cart;
import entity.Product_Info;
import entity.User;
import entity.Warehouse_Product;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


import xuli.dao.UserDao;


import xuli.dao.WareHouseProductDao;
import xuli.dao.impl.UserDaoImpl;
import xuli.dao.impl.WareHouseProductDaoImpl;
import xuli.service.ProductHomeService;
import xuli.service.ShoppingCartService;
import xuli.service.impl.ProductHomeServiceImpl;
import xuli.service.impl.ShoppingCartServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/ShoppingCartServlet")
public class ShoppingCartServlet extends HttpServlet {
    private UserDao userDao = new UserDaoImpl();
    /**
     * 添加到购物车
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        HashMap<String, Object> user = getUser(request, response);
        if(user == null){
            return;
        }
        Integer userId = (Integer) user.get("userId");
        HashMap<String, Object> stringBooleanHashMap = new HashMap<>();
        if (userId == null || userId == 0) {
            stringBooleanHashMap.put("status", false);
            return;
        } else {
            ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
            List<FileItem> fileItems = null;
            try {
                fileItems = servletFileUpload.parseRequest(request);
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
            Class<Order_Cart> order_cartClass = Order_Cart.class;
            Order_Cart order_cart = null;
            try {
                order_cart = order_cartClass.getDeclaredConstructor().newInstance();
            } catch (InstantiationException | InvocationTargetException | NoSuchMethodException | IllegalAccessException e) {
                e.printStackTrace();
            }
            if (fileItems != null) {
                for (FileItem fileItem : fileItems) {
                    if (fileItem.isFormField()) {
                        try {
                            String fieldName = fileItem.getFieldName();
                            PropertyDescriptor propertyDescriptor = new PropertyDescriptor(fieldName, order_cartClass);
                            Method writeMethod = propertyDescriptor.getWriteMethod();
                            String simpleName = propertyDescriptor.getPropertyType().getSimpleName();
                            if ("Integer".equals(simpleName)) {
                                writeMethod.invoke(order_cart, Integer.parseInt(fileItem.getString()));
                            } else if ("String".equals(simpleName)) {
                                writeMethod.invoke(order_cart, fileItem.getString());
                            } else {
                                System.out.println("不支持其他格式");
                            }
                        } catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            ProductHomeService phs = new ProductHomeServiceImpl();
            WareHouseProductDao wareHouseProductDao = new WareHouseProductDaoImpl();
            Product_Info productInfo = phs.findProductById(order_cart.getProduct_id());
            double price = productInfo.getPrice();
            order_cart.setUser_id(userId);
            order_cart.setPrice((float) price);
            order_cart.setAdd_time(new Date());
            order_cart.setModified_time(new Date());
            ShoppingCartService shoppingCartService = new ShoppingCartServiceImpl();
            boolean insert = shoppingCartService.insert(order_cart);
            Warehouse_Product byIdAndModelId = wareHouseProductDao.findByIdAndModelId(order_cart.getProduct_id().toString(), order_cart.getModel_id());
            byIdAndModelId.setCurrent_cnt(byIdAndModelId.getCurrent_cnt() - order_cart.getProduct_amount());
            wareHouseProductDao.reduceInventory(byIdAndModelId);
            stringBooleanHashMap.put("status", insert);
        }
        String s = JSON.toJSONString(stringBooleanHashMap);
        response.getWriter().print(s);
    }


    /**
     * 获取用户购物车信息
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        HashMap<String, Object> user = getUser(request, response);
        if(user == null){
            return;
        }
        Integer userId = (Integer) user.get("userId");
        Map<String, Object> stringObjectHashMap = new HashMap<>();
        ShoppingCartService shoppingCartService = new ShoppingCartServiceImpl();
        List<Order_Cart> orderCarts = shoppingCartService.findAll(userId);
        stringObjectHashMap.put("status", "1");
        stringObjectHashMap.put("orderCarts", orderCarts);
        String s = JSON.toJSONString(stringObjectHashMap);
        response.getWriter().print(s);
    }


    /**
     * 是否登录信息
     *
     * @param request
     * @return
     */
    private HashMap<String, Object> getUser(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        HttpSession session = request.getSession();
        String contextPath = request.getContextPath();
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        User user = (User) session.getAttribute("SywUser");
        if (user == null) {
            session.setAttribute("msg", "未登录");
            stringObjectHashMap.put("redirectUrl", contextPath + "/errorInfo.jsp");
            String s = JSON.toJSONString(stringObjectHashMap);
            response.getWriter().print(s);
            return null;
        }
        User checkUser = userDao.queryUserByLoginNameAndPassword(user.getUsername(), user.getPassword());
        if (checkUser == null) {
            session.setAttribute("msg", "账号已修改,请重新登陆");
            stringObjectHashMap.put("redirectUrl", contextPath + "/errorInfo.jsp");
            String s = JSON.toJSONString(stringObjectHashMap);
            response.getWriter().print(s);
            return null;
        }
        stringObjectHashMap.put("userId", checkUser.getUserId());
        return stringObjectHashMap;
    }
}
